package request

import (
	"github.com/gin-gonic/gin"
	"net/url"
	"time"
)

// PageInfo Paging common input parameter structure
type PageInfo struct {
	Page     int `json:"pageNum" form:"pageNum"`   // 页码
	PageSize int `json:"pageSize" form:"pageSize"` // 每页大小
}

const (
	cParamsKey = "params"
)

type BaseRequest struct {
	queryParams *url.Values
	Params      map[string]interface{}
}
type IDRequest struct {
	ID uint64 `json:"id,string" form:"id,string" binding:"required"`
}
type IDRequestOptional struct {
	ID uint64 `json:"id,string" form:"id,string"`
}

func (p *PageInfo) Offset() int {
	if p.Page == 0 {
		p.Page = 1
	}
	if p.PageSize == 0 {
		p.PageSize = 10
	}
	return (p.Page - 1) * p.PageSize
}
func (p *PageInfo) Limit() int {
	if p.PageSize == 0 {
		p.PageSize = 10
	}
	return p.PageSize
}

// by query
func (b *BaseRequest) ShouldBindParams(c *gin.Context) {
	queryParams := c.Request.URL.Query()
	if queryParams == nil {
		return
	}
	b.queryParams = &queryParams
}

/*
bool: exists
*/
func (b *BaseRequest) GetParamValue(key string) (string, bool) {
	if b.queryParams == nil {
		return "", false
	}
	return b.queryParams.Get(b.fmtParamKey(key)), true
}

func (b *BaseRequest) FormatBeginTime(beginTime string) string {
	t, err := time.Parse("2006-01-02 15:04:05", beginTime)
	if err != nil {
		t, err = time.Parse("2006-01-02", beginTime)
		if err != nil {
			return ""
		}
	}
	return t.Format("2006-01-02") + " 00:00:00"
}

func (b *BaseRequest) FormatEndTime(endTime string) string {

	t, err := time.Parse("2006-01-02 15:04:05", endTime)
	if err != nil {
		t, err = time.Parse("2006-01-02", endTime)
		if err != nil {
			return ""
		}
	}
	return t.Format("2006-01-02") + " 23:59:59"
}

func (b *BaseRequest) fmtParamKey(key string) string {
	return cParamsKey + "[" + key + "]"
}
